<?php
/**
 * 数据库类
 *
 * @copyright	http://www.easymvc.com
 * @author 		光哥  <439884988@qq.com>
 * @version		1.0 - 2012-03-26
 * @package		Lib
 *
 */
if(!defined('EASYMVC')) {
	exit('Access Denied');
}
/**
 * 普通
 */
class Lib_Db_Mysql {

	var $link = null;

	function connect($dbhost,$port=3306, $dbname = '',$dbuser, $dbpw, $pconnect = 0) {
		$dbhost.= ":$port";
		$func = empty($pconnect) ? 'mysql_connect' : 'mysql_pconnect';
		if(!$this->link = @$func($dbhost, $dbuser, $dbpw, 1)) {
				if(!$this->link = @$func($dbhost, $dbuser, $dbpw, 1)){
					throw new Frame_Exception_Program('MySQL Connection Database Error: ' . mysql_error());
				}
		} 
		$dbname && @mysql_select_db($dbname, $this->link);
	}

	function fetchColumn($sql, $result_type = MYSQL_ASSOC) {
		$query = $this->query($sql);
		return mysql_fetch_array($query, $result_type);
	}

	function fetchAll($sql,$result_type = MYSQL_ASSOC) {
		$result = array();
		$query = $this->query($sql);
		while($row = mysql_fetch_array($query, $result_type)){
			$result[] = $row;
		}
		return $result;
	}
	/**
	 * 获取表总数
	 * @param string $table
	 * @param array $cond
	 */
	function fethcCount($table,$where=''){
		$where = $this->rendWhere($where);
		$sql = "select count(*) as num from $table $where";
		$result = $this->fetchColumn($sql);
		return $result['num'];
	}
	
	function rendWhere($data_array){
		$cond = 'where 1=1 ';
		if(!is_array($data_array)) return $data_array;
		foreach($data_array as $coloum=>$value){
			
			$cond .= " AND $coloum='".$this->quote($value)."' ";
		}
		return $cond;
	}

	function query($sql, $type = '') {

		$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
			'mysql_unbuffered_query' : 'mysql_query';
		if(!($query = $func($sql, $this->link))) {
			throw new Frame_Exception_Program('Query Error: ' . mysql_error());
		}
		return $query;
	}
	/**
	 * 影响行数 delete | modify
	 * @return bool
	 */
	function affect_rows(){
		return mysql_affected_rows($this->link);
	}
    /**
     * 返回增加的行
     * @return number
     */
	function insert_id() {
		return mysql_insert_id($this->link);
	}
	function quote( $string )
	{
		return "'" . mysql_real_escape_string( $string, $this->link ) . "'";
	}
	
	function insert($table,$data){
	
	foreach($data as $key => $value) {
			$setAr[] = "`{$key}`=".$this->quote($value);
			//$valAr[] = $value;
		}
		$setStr = implode(",",$setAr);
		$sql = "insert into $table set {$setStr}";
	
		return $this->query($sql);
	}
	
	function update($table,$data,$where){
		
		if(!is_array($data)) return false;
		$where = $this->rendWhere($where);
		foreach($data as $key => $value) {
			$setAr[] = "`{$key}`=".$this->quote($value);
			//$valAr[] = $value;
		}
		$setStr = implode(',', $setAr);
		$sql = "UPDATE `charity` SET {$setStr} $where";

		return $this->query($sql);
	}
	
	function __construct() {
		return $this->link ? mysql_close($this->link) : true;
	}
}

?>